import sys

from PyQt5.Qt import *

from UI.form import Ui_Form
import numpy as np
import pyqtgraph as pg
from pyqtgraph import PlotItem


class SelectWindow(QDialog, Ui_Form):

    requestChangeMinMaxFreq = pyqtSignal(tuple)

    def __init__(self, parent, y,  f0 = 300, fs=100, nfft=2048):
        super(SelectWindow, self).__init__(parent)
        self.setupUi(self)

        self.f0 = f0
        self.fs = fs
        self.nfft = nfft
        self.resolution = self.fs / self.nfft
        self.y = y
        self.lineEdit_resolution.setText("%.5f" % self.resolution)
        x2 = np.linspace(self.f0 - self.fs / 2, self.f0 + self.fs / 2, self.nfft)
        print("x2.shape = ", x2.shape)
        # self.limits = [x2.min(), x2.max()]
        self.limits = [x2.min(), x2.max()]
        self.doubleSpinBox_begin.setMinimum(self.limits[0])
        self.doubleSpinBox_end.setMinimum(self.limits[0])

        self.doubleSpinBox_begin.setMaximum(self.limits[1])
        self.doubleSpinBox_end.setMaximum(self.limits[1])
        #
        # qss = '''
        # *:hover{
        #     background-color:green;
        # }
        # '''
        # self.pushButton_over.setStyleSheet(qss)
        self.pushButton_over.clicked.connect(self.close)

        data2 = self.y
        self.plot_item: PlotItem = self.widget.plotItem
        self.plot_item.setTitle(title="<b>信号频谱图</b>")
        self.plot_item.setLabel(axis='bottom', text = "<b>频率(MHz)</b>")
        self.plot_item.setLabel(axis='left', text="<b>振幅</b>")

        self.ori_plot = self.plot_item.plot(pen=(255, 255, 255, 200))
        self.ori_plot.setData(x2, data2)

        self.lr = pg.LinearRegionItem(self.limits)
        self.lr.setZValue(-10)
        self.plot_item.addItem(self.lr)

        self.zoom_item: PlotItem = self.widget_2.plotItem
        self.zoom_item.setTitle(title="<b>局部信号频谱图</b>")
        self.zoom_item.setLabel(axis='bottom', text="<b>频率(MHz)</b>")
        self.zoom_item.setLabel(axis='left', text="<b>振幅</b>")
        self.zoom_plot = self.zoom_item.plot(pen=(255, 255, 255, 200))
        self.zoom_plot.setData(x2, data2)

        self.lr.sigRegionChangeFinished.connect(self.checkRegion)

        self.lr.sigRegionChanged.connect(self.updatePlot)
        self.zoom_item.sigXRangeChanged.connect(self.updateRegion)
        self.pushButton_confirm.clicked.connect(self.changeRegion)
        self.updatePlot()

    def changeRegion(self):
        l = self.doubleSpinBox_begin.value()
        r = self.doubleSpinBox_end.value()
        if r <= l:
            QMessageBox.critical(self, "错误提示", "终止频率应大于起始频率!")
            l = self.lr.getRegion()[0]
            r = self.lr.getRegion()[1]
            self.doubleSpinBox_begin.setValue(l)
            self.doubleSpinBox_end.setValue(r)
            self.lineEdit_bandwidth.setText("%.5f" % (r - l))
            return
        self.lr.setRegion([l, r])


    def checkRegion(self):
        lines = self.lr.getRegion()
        if self.limits[0] <= lines[0] <= self.limits[1] and self.limits[0] <= lines[1] <= self.limits[1]:
            return
        else:
            left = lines[0] if self.limits[0] <= lines[0] <= self.limits[1] else self.limits[0]
            right = lines[1] if self.limits[0] <= lines[1] <= self.limits[1] else self.limits[1]
            self.lr.setRegion((left, right))

    def updatePlot(self):
        region = self.lr.getRegion()
        self.zoom_item.setXRange(*region, padding=0)
        tmp = region[0] % self.resolution
        # rest = 1 if tmp >= self.resolution / 2 else 0
        # # left = (region[0] // self.resolution + rest) * self.resolution
        left = region[0]
        self.doubleSpinBox_begin.setValue(left)
        # tmp = region[1] % self.resolution
        # rest = 1 if tmp >= self.resolution / 2 else 0
        # right = (region[1] // self.resolution + rest) * self.resolution
        right = region[1]
        self.doubleSpinBox_end.setValue(right)
        self.lineEdit_bandwidth.setText("%.5f" % (right - left))

    def updateRegion(self):
        self.lr.setRegion(self.zoom_item.getViewBox().viewRange()[0])

    def closeEvent(self, a0: QCloseEvent) -> None:
        a0.accept()
        l = self.doubleSpinBox_begin.value()
        r = self.doubleSpinBox_end.value()
        self.requestChangeMinMaxFreq.emit((l, r))

